using System;
using System.Xml;
using System.IO;
using System.Text;
using System.Data;
using System.Collections;
using Castle.Facilities.NHibernateIntegration;
using Castle.Services.Transaction;
using NHibernate;
using BEGDC.Utility.Email;
using BEGDC.Utility.Castle;
using BEGDC.CC.BL.Email;
using ASB.CC.EmailService;

namespace CCEmailService
{
	/// <summary>
	/// Summary description for ProjectService.
	/// </summary>
	public class EmailService : IEmail
	{
		private ISessionManager sessionManager;
		private string _SenderEmail = System.Configuration.ConfigurationSettings.AppSettings["SenderEmail"];

		public EmailService(ISessionManager sessionManager)
		{
			this.sessionManager = sessionManager;
		}
		#region Email Members

		[Transaction(TransactionMode.Requires)]
		public void SendEmails()
		{
			using ( ISession session = sessionManager.OpenSession() )
			{
				BEGDC.CC.BL.Email.IEmail emailService = (BEGDC.CC.BL.Email.IEmail) AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.EmailService];

				BEGDC.CC.BL.Common.Query.IQuery iquery = AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.QueryService] as  BEGDC.CC.BL.Common.Query.IQuery;
			

				//Add by Tomorrow on 01/03/2007 - start
				//Add New Family Notifaction record to Table
				//string str = this.InsertNewFamilyRecord(emailService);
				//Add by Tomorrow on 01/03/2007 - end

				IList mailList = emailService.GetEmailList(session);

				string websiteurl = System.Configuration.ConfigurationSettings.AppSettings["CCWebSiteURL"];
				
				for( int i=0; i < mailList.Count; i++ )
				{
					BEGDC.CC.Entity.Email email = null;
					try
					{
						email = mailList[i] as BEGDC.CC.Entity.Email;
						string templateKey = email.TemplateName;
					
					
						int mailID = email.Id;
				
						BEGDC.CC.Entity.Application application = email.Application;
					
						if( application == null )
							continue;
					
						//Load XML Template
						XmlDocument xmlDoc = new XmlDocument();
						string from = string.Empty;
						string to = string.Empty;
						string cc = string.Empty;
						string subject = string.Empty;
						string body = string.Empty;			
						string nameEN = string.Empty;
						string nameCN = string.Empty;
						string path = Utility.GetTemplateFile(email.TemplateName + ".xml");
						if( !File.Exists( path ))
						{

                            string path1 = System.Environment.CurrentDirectory + "\\asbcc_error.log";
                            StringBuilder sb = new StringBuilder();
                            sb.Append("Template not found : " + path);
                            FileStream fs = File.Open(path1, FileMode.Append, FileAccess.Write);
                            StreamWriter sw = new StreamWriter(fs);
                            sw.Write(sb.ToString());
                            sw.Close();
                            fs.Close();

							string toTemp = System.Configuration.ConfigurationSettings.AppSettings["AdminEmail"];
							SendMail("",toTemp, "", "Error", " No Template named " + templateKey + " existed !");
							this.UpdateSendMail( session, email );
							continue;
						}						
						xmlDoc.Load(path);						
						to = GetNodeValue(xmlDoc,"//Template/To");
						from = GetNodeValue(xmlDoc,"//Template/From");
						cc = GetNodeValue(xmlDoc, "//Template/CC");
						subject = GetNodeValue(xmlDoc,"//Template/Subject");
						subject = subject.Replace("&amp;", "&");
						body = GetNodeValue(xmlDoc,"//Template/Body");
						body = body.Replace("{CCWebSiteURL}", websiteurl);

						IEmailTemplate template = null;

						//AP
						if (email.TemplateName == "AP_EndAP" || email.TemplateName == "AP_FillAPRequest")
						{
							string sql = " select * from vw_APInfo where AppID = " + application.Id;
							System.Data.DataTable dtAP = BEGDC.Utility.NHibernate.NHibernateUtil.Execute(session,sql);
							foreach(System.Data.DataRow drAP in dtAP.Rows)
							{
								int apid = Convert.ToInt32(drAP["APID"].ToString());

								BEGDC.CC.Entity.ActionPoint ap = session.Get( typeof(BEGDC.CC.Entity.ActionPoint), apid ) as BEGDC.CC.Entity.ActionPoint;
								string emails = string.Empty;
								string nameen = "AP Owner/AP Contributer";
								string namecn = "AP Owner/AP Contributer";

								foreach(BEGDC.CC.Entity.APPartner apPartner in ap.APPartners)
								{
									if (apPartner.Employee.Email != null)
										emails += apPartner.Employee.Email + ";";
									if (ap.APPartners.Count == 1)
									{
										nameen = apPartner.Employee.NameCN;
										namecn = apPartner.Employee.NameChinese;
									}
								}
					

								if (emails == string.Empty) continue;

								string templatexml = this.LoadTemplate(Utility.GetTemplateFile("Reminder_AP.xml"));

								templatexml = templatexml.Replace("{CCWebSiteURL}", websiteurl);
								templatexml = templatexml.Replace("{Priority}", ap.Priority);
								templatexml = templatexml.Replace("{DueTime}", ap.DueTime.Value.ToString("M/d/yyyy"));
								templatexml = templatexml.Replace("{APNo}", ap.APNo);
								templatexml = templatexml.Replace("{APID}", ap.Id.ToString());
								templatexml = templatexml.Replace("{MeetingID}", ap.EVMeeting.Id.ToString());

								templatexml = templatexml.Replace("{UserNameEN}", nameen);
								templatexml = templatexml.Replace("{UserNameCN}", namecn);


								to = emails;
								cc = string.Empty;
								body = templatexml;
								//this.SendMail(_SenderEmail, emails, string.Empty, "Customer Case: AP Reminder", templatexml);

								if (!SendMail(from, to, cc, subject, body))
								{
									string path1 = System.Environment.CurrentDirectory+"\\asbcc_error.log";
									StringBuilder sb = new StringBuilder();
									sb.Append("============================================\r\n");
									sb.AppendFormat("Sended fail--To:{0}Subject:{1}--EmailID:{2}\r\n",to,subject, mailID);
									FileStream fs = File.Open(path1,FileMode.Append,FileAccess.Write);	
									StreamWriter sw = new StreamWriter(fs);
									sw.Write(sb.ToString());
									sw.Close();
									fs.Close();								
								}
								else
								{
									// Write Log
									BEGDC.CC.BL.Common.IUtility utility = AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.UtilityService] as BEGDC.CC.BL.Common.IUtility;
									BEGDC.CC.Entity.OperationLog log = new BEGDC.CC.Entity.OperationLog();
									log.Module = application.ApplicationType;
									log.OperationType = ((BEGDC.CC.Entity.FlowInstance)application.FlowInstances[0]).State.StateName;
									BEGDC.CC.Entity.Employee emp = new BEGDC.CC.Entity.Employee();
									emp.Id = "EmailService";
									log.Employee = emp;
									log.Time = System.DateTime.Now;
									log.Description = "Send To:" + to + ". CC: " + cc + ". subject:" + subject;
									log.AppNO = application.AppNo;
									log.CurrentStep = ((BEGDC.CC.Entity.FlowInstance)application.FlowInstances[0]).CurrentActiveStep.StepName;
									utility.SaveOperationLog(log);
								}
							}
							
							sql = string.Format(" UPDATE    Email SET  IsSend =1, SendTime =getdate() where AppId = {0} AND (TemplateName = 'AP_EndAP') ", application.Id.ToString());
							BEGDC.Utility.NHibernate.NHibernateUtil.ExecuteNonQuery(session, sql);
							return;
						}
						//AP Comments
						else if (email.TemplateName == "EV_APComment")
						{
							string sql = " select * from vw_APInfo where AppID=" + application.Id + " and APID=" + email.ApID.ToString();
							System.Data.DataTable dtAP = BEGDC.Utility.NHibernate.NHibernateUtil.Execute(session,sql);
							foreach(System.Data.DataRow drAP in dtAP.Rows)
							{
								int apid = Convert.ToInt32(drAP["APID"].ToString());

								BEGDC.CC.Entity.ActionPoint ap = session.Get( typeof(BEGDC.CC.Entity.ActionPoint), apid ) as BEGDC.CC.Entity.ActionPoint;
//								string templatexml = this.LoadTemplate(System.Configuration.ConfigurationSettings.AppSettings["TemplatePath"].ToString() + "EV_APComment.xml");

								body = body.Replace("{CCWebSiteURL}", websiteurl);
								body = body.Replace("{APNo}", ap.APNo);
								if(ap.APCommentses.Count > 0)
								{
									BEGDC.CC.Entity.APComment comment = (BEGDC.CC.Entity.APComment)ap.APCommentses[ap.APCommentses.Count-1];
									body = body.Replace("{APAnswerBy}", comment.AnsweredBy);
								}
//								body = templatexml;

								if( to != string.Empty )
								{
									to = EmailTemplateResolver.ResolverReceiver(to, application, out nameEN, out nameCN );
								}
								if( cc != string.Empty )
								{
									cc = EmailTemplateResolver.ResolverReceiver( cc, application );
								}

								if (!SendMail(from, to, cc, subject, body))
								{
									string path1 = System.Environment.CurrentDirectory+"\\asbcc_error.log";
									StringBuilder sb = new StringBuilder();
									sb.Append("============================================\r\n");
									sb.AppendFormat("Sended fail--To:{0}Subject:{1}--EmailID:{2}\r\n",to,subject, mailID);
									FileStream fs = File.Open(path1,FileMode.Append,FileAccess.Write);	
									StreamWriter sw = new StreamWriter(fs);
									sw.Write(sb.ToString());
									sw.Close();
									fs.Close();								
								}
								else
								{
									// Write Log
									BEGDC.CC.BL.Common.IUtility utility = AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.UtilityService] as BEGDC.CC.BL.Common.IUtility;
									BEGDC.CC.Entity.OperationLog log = new BEGDC.CC.Entity.OperationLog();
									log.Module = application.ApplicationType;
									log.OperationType = ((BEGDC.CC.Entity.FlowInstance)application.FlowInstances[0]).State.StateName;
									BEGDC.CC.Entity.Employee emp = new BEGDC.CC.Entity.Employee();
									emp.Id = "EmailService";
									log.Employee = emp;
									log.Time = System.DateTime.Now;
									log.Description = "Send To:" + to + ". CC: " + cc + ". subject:" + subject;
									log.AppNO = application.AppNo;
									log.CurrentStep = ((BEGDC.CC.Entity.FlowInstance)application.FlowInstances[0]).CurrentActiveStep.StepName;
									utility.SaveOperationLog(log);

									email.IsSend = true;
									email.SendTime = System.DateTime.Now;
								}
							}
							
//							sql = string.Format(" UPDATE    Email SET  IsSend =1, SendTime =getdate() where AppId = {0} AND (TemplateName = 'AP_EndAP') ", application.Id.ToString());
//							BEGDC.Utility.NHibernate.NHibernateUtil.ExecuteNonQuery(session, sql);
							this.UpdateSendMail( session, email );
							return;
                        }
                        #region cacel mail
                        else if (email.TemplateName == "CancelMail")
						{
							string sql = " select actor,email from ActionLog inner join employee on actionlog.actor = employee.nameen";
									sql += " where AppID=" + application.Id + " group by actor,email";
							System.Data.DataTable dtActor = BEGDC.Utility.NHibernate.NHibernateUtil.Execute(session,sql);

							body = body.Replace("{CCWebSiteURL}", websiteurl);
							body = body.Replace("{APPNo}", application.AppNo);

							foreach(System.Data.DataRow drActor in dtActor.Rows)
							{
								if( to == string.Empty )
								{
									to = drActor["email"].ToString();
								}
								else
								{
									to += ";"+drActor["email"].ToString();
								}								
							}

							if (!SendMail(from, to, cc, subject, body))
							{
								string path1 = System.Environment.CurrentDirectory+"\\asbcc_error.log";
								StringBuilder sb = new StringBuilder();
								sb.Append("============================================\r\n");
								sb.AppendFormat("Sended fail--To:{0}Subject:{1}--EmailID:{2}\r\n",to,subject, mailID);
								FileStream fs = File.Open(path1,FileMode.Append,FileAccess.Write);	
								StreamWriter sw = new StreamWriter(fs);
								sw.Write(sb.ToString());
								sw.Close();
								fs.Close();								
							}
							else
							{
								// Write Log
								BEGDC.CC.BL.Common.IUtility utility = AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.UtilityService] as BEGDC.CC.BL.Common.IUtility;
								BEGDC.CC.Entity.OperationLog log = new BEGDC.CC.Entity.OperationLog();
								log.Module = application.ApplicationType;
								log.OperationType = ((BEGDC.CC.Entity.FlowInstance)application.FlowInstances[0]).State.StateName;
								BEGDC.CC.Entity.Employee emp = new BEGDC.CC.Entity.Employee();
								emp.Id = "EmailService";
								log.Employee = emp;
								log.Time = System.DateTime.Now;
								log.Description = "Send To:" + to + ". CC: " + cc + ". subject:" + subject;
								log.AppNO = application.AppNo;
								log.CurrentStep = ((BEGDC.CC.Entity.FlowInstance)application.FlowInstances[0]).CurrentActiveStep.StepName;
								utility.SaveOperationLog(log);

								email.IsSend = true;
								email.SendTime = System.DateTime.Now;
							}

							this.UpdateSendMail( session, email );
							return;
                        }

                        #endregion
                        else
						{

							if(body != string.Empty)
							{
								body = EmailTemplateResolver.ResolveEmailTemplate(body,iquery.QueryFlowInstance(application.Id)).Replace("\"", "'");
							}
						
							if (body == "Assembly")
							{
								template = AppContainer.Instance[templateKey] as IEmailTemplate;
								if (template != null)
									body = template.GetBody(application.Id);
								else
									body = string.Empty;
							}

							if( to != string.Empty )
							{
								to = EmailTemplateResolver.ResolverReceiver(to, application, out nameEN, out nameCN );
								body = body.Replace("{UserNameEN}",nameEN);
								body = body.Replace("{UserNameCN}",nameCN);

							}
						
							if (to == "Assembly")
							{
								if (template == null)
									template = AppContainer.Instance[templateKey] as IEmailTemplate;
								if (template != null)
									to = template.GetTo(application.Id);
								else
									to = string.Empty;
							}

							if( cc != string.Empty )
							{
								cc = EmailTemplateResolver.ResolverReceiver( cc, application );
							}
						
							if (cc == "Assembly")
							{
								if (template == null)
									template = AppContainer.Instance[templateKey] as IEmailTemplate;
								if (template != null)
									cc = template.GetCC(application.Id);
								else
									cc = string.Empty;
							}

							if (!SendMail(from, to, cc, subject, body))
							{
								string path1 = System.Environment.CurrentDirectory+"\\asbcc_error.log";
								StringBuilder sb = new StringBuilder();
								sb.Append("============================================\r\n");
								sb.AppendFormat("Sended fail--To:{0}Subject:{1}--EmailID:{2}\r\n",to,subject, mailID);
								FileStream fs = File.Open(path1,FileMode.Append,FileAccess.Write);	
								StreamWriter sw = new StreamWriter(fs);
								sw.Write(sb.ToString());
								sw.Close();
								fs.Close();				
							}
							else
							{
								// Write Log
								BEGDC.CC.BL.Common.IUtility utility = AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.UtilityService] as BEGDC.CC.BL.Common.IUtility;
								BEGDC.CC.Entity.OperationLog log = new BEGDC.CC.Entity.OperationLog();
								log.Module = application.ApplicationType;
								log.OperationType = ((BEGDC.CC.Entity.FlowInstance)application.FlowInstances[0]).State.StateName;
								BEGDC.CC.Entity.Employee emp = new BEGDC.CC.Entity.Employee();
								emp.Id = "EmailService";
								log.Employee = emp;
								log.Time = System.DateTime.Now;
								log.Description = "Send To:" + to + ". CC: " + cc + ". subject:" + subject;
								log.AppNO = application.AppNo;
								log.CurrentStep = ((BEGDC.CC.Entity.FlowInstance)application.FlowInstances[0]).CurrentActiveStep.StepName;
								utility.SaveOperationLog(log);

								email.IsSend = true;
								email.SendTime = System.DateTime.Now;
							}
						}

						this.UpdateSendMail( session, email );
					}
					catch(Exception err)
					{
						
						string path1 = System.Environment.CurrentDirectory+"\\asbcc_error.log";
						StringBuilder sb = new StringBuilder();
						sb.Append("============================================\r\n");
						sb.AppendFormat("Sended fail--{0}",err.Message);
						FileStream fs = File.Open(path1,FileMode.Append,FileAccess.Write);	
						StreamWriter sw = new StreamWriter(fs);
						sw.Write(sb.ToString());
						sw.Close();
						fs.Close();
						try
						{
							if (email != null)
							{
								email.IsSend = true;
								email.SendTime = System.DateTime.Now;
								this.UpdateSendMail( session, email );
							}

							string address = System.Configuration.ConfigurationSettings.AppSettings["AdminEmail"];
							SendMail("",address, "", "Error", err.Message);
						}
						catch
						{
						}
					}
				}
				
			}

		}

		
		public bool SendMail(String from, String to, String cc, String subject, String body)
		{
			try
			{
				IMailMessage  mail = new EmailBySMTPFactory().GetEmailInstance();
				mail.MailServer = System.Configuration.ConfigurationSettings.AppSettings["MailServer"];
				mail.From =  from;
				mail.To = to;
				mail.CC = cc;
				mail.Subject = subject;
				mail.Body = body;
				mail.BodyFormat= System.Web.Mail.MailFormat.Html;
				return mail.Send();
			}
			catch 
			{
				string path1 = System.Environment.CurrentDirectory+"\\asbcc_error.log";
				StringBuilder sb = new StringBuilder();
				sb.Append("============================================\r\n");
				sb.AppendFormat("Sended fail--To:{0}Subject:{1}--EmailID:{2}\r\n",to,subject, string.Empty);
				FileStream fs = File.Open(path1,FileMode.Append,FileAccess.Write);	
				StreamWriter sw = new StreamWriter(fs);
				sw.Write(sb.ToString());
				sw.Close();
				fs.Close();					
				return false;
			}
		}


		private void UpdateSendMail(ISession session, BEGDC.CC.Entity.Email mail)
		{
			try
			{
				mail.IsSend = true;
				mail.SendTime = DateTime.Now;
				session.Update(mail, mail.Id);
				session.Flush();
			}
			catch(Exception ex)
			{
				System.Diagnostics.Debug.WriteLine(ex.Message);
			}
		}

		private string LoadTemplate( string templateName )
		{
			if( !File.Exists( templateName ) )
				return null;
			
			System.IO.TextReader tr = System.IO.File.OpenText(templateName);
			string xml = tr.ReadToEnd();

			tr.Close();
				
			//			XmlDocument templateDoc = new XmlDocument();
			//			templateDoc.Load( templateName );
			
			return xml;
		}

		public string GetNodeValue(XmlDocument templateDoc, string xPath )
		{
			if (templateDoc == null)
				return string.Empty;

			XmlNode node = templateDoc.SelectSingleNode(xPath);
			if (node != null)
				return node.InnerXml;
			return string.Empty;
		}

		/// <summary>
		/// Insert new family record to table: Email.
		/// Added by Tomorrow on 01/03/2007.
		/// </summary>
		private string InsertNewFamilyRecord(BEGDC.CC.BL.Email.IEmail pi_EmailService)
		{
//			BEGDC.CC.BL.LeadTime.ILeadTime iLeadTime = (BEGDC.CC.BL.LeadTime.ILeadTime)AppContainer.Instance["CCBL.LeadTime"];
//			DataTable dt = iLeadTime.GetFamilyMapping();
//			GDC.CC.ExtSysSimulator.SAP.ISAPSimulator iSAPSimulator = new GDC.CC.ExtSysSimulator.SAP.SAPSimulatorService();
//			Hashtable ht = new Hashtable();
//			GDC.CC.ExtSysSimulator.SAP.SAPFamilyInfo dt_SAPFamily = iSAPSimulator.GetFamilyCode(ht);

			string str = "";
//			for(int i = 0; i < dt.Rows.Count; i++)
//			{
//				str += "'" + dt.Rows[i]["Family"].ToString().Trim().Replace("'", "''") + "', ";
//			}
//
//			str.Substring(0, str.Length - 2);
//
//			DataView dv = new DataView((DataTable)dt_SAPFamily, GDC.CC.ExtSysSimulator.SAP.SAPFamilyInfo.FamilyCode + " NOT IN (" + str + ")", "", DataViewRowState.CurrentRows);
//
//			if (dv.Count > 0)
//			{
//				BEGDC.CC.Entity.Email email = new BEGDC.CC.Entity.Email();
//				email.IsSend = false;
//				email.TemplateName = "Family_Notification";
//			}
//
//			str = "";
//
//			for (int j = 0; j < dv.Count; j++)
//			{
//				str += dv[j][GDC.CC.ExtSysSimulator.SAP.SAPFamilyInfo.FamilyCode].ToString().Trim() + ", ";
//			}
//
//			str.Substring(0, str.Length - 2);

            return str;
		}

		private System.DateTime _newtime = System.DateTime.Now;

		/// <summary>
		/// Send reminder
		/// </summary>
		[Transaction(TransactionMode.Requires)]
		public void SendReminder()
		{
			if (_newtime > System.DateTime.Now)
				return;

			System.DateTime process_time = System.DateTime.Now;

			try
			{
				//Role

				string websiteurl = System.Configuration.ConfigurationSettings.AppSettings["CCWebSiteURL"];


				using ( ISession session = sessionManager.OpenSession() )
				{
					//Get user by modified

					string sql = "select DISTINCT e from e in class BEGDC.CC.Entity.Employee, p in class BEGDC.CC.Entity.UserRole where e.Id = p.Employee.Id and modifytype = 'Role' and modifydatetime >= '" + _newtime.ToString() + "'";
					System.Collections.IList employees = session.Find(sql);	
					foreach(BEGDC.CC.Entity.Employee emp in employees)
					{
						sql = " from UserRole where employeeno = '" +  emp.Id + "'";

						System.Collections.IList userroles = session.Find(sql);	
						string rolelist =  string.Empty;
						foreach(BEGDC.CC.Entity.UserRole userrole in userroles)
						{
							rolelist += userrole.Role.Description  + "; ";
						}

						string templatexml = this.LoadTemplate(Utility.GetTemplateFile("Reminder_UserRoleModified.xml"));

						templatexml = templatexml.Replace("{CCWebSiteURL}", websiteurl);
						templatexml = templatexml.Replace("{UserNameEN}",emp.NameEN);
						templatexml = templatexml.Replace("{UserNameCN}",emp.NameCN);
						templatexml = templatexml.Replace("{Roles}",rolelist);

						if (emp.Email == null || emp.Email == string.Empty)	continue;
						if (!this.SendMail(_SenderEmail, emp.Email, string.Empty, "Customer Case: User Role Modified", templatexml))
						{
							string path1 = System.Environment.CurrentDirectory+"\\asbcc_error.log";
							StringBuilder sb = new StringBuilder();
							sb.Append("============================================\r\n");
							sb.AppendFormat("Sended fail--To:{0}Subject:{1}--EmailID:{2}\r\n",emp.Email,"Customer Case: User Role Modified", "Reminder_UserRoleModified.xml");
							FileStream fs = File.Open(path1,FileMode.Append,FileAccess.Write);	
							StreamWriter sw = new StreamWriter(fs);
							sw.Write(sb.ToString());
							sw.Close();
							fs.Close();								
						}
						else
						{
							// Write Log
							BEGDC.CC.BL.Common.IUtility utility = AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.UtilityService] as BEGDC.CC.BL.Common.IUtility;
							BEGDC.CC.Entity.OperationLog log = new BEGDC.CC.Entity.OperationLog();
							log.Module = "Reminder";
						
							BEGDC.CC.Entity.Employee empemail = new BEGDC.CC.Entity.Employee();
							empemail.Id = "EmailService";
							log.Employee = empemail;
							log.Time = System.DateTime.Now;
							log.Description = "Send To:" + emp.Email + ". subject:Customer Case: User Role Modified" ;
						
							utility.SaveOperationLog(log);
						}

					}
					
				}

				//Delegration

				using ( ISession session = sessionManager.OpenSession() )
				{
					//Get user by modified

					string sql = "from UserRole where modifytype = 'Delegation' and modifydatetime >= '" + _newtime.ToString() + "'";
					System.Collections.IList userroles = session.Find(sql);	
					foreach(BEGDC.CC.Entity.UserRole userrole in userroles)
					{
					
						if(userrole.DelegateUser == null)	continue;

						string templatexml = this.LoadTemplate(Utility.GetTemplateFile("Reminder_UserRoleDelegation.xml"));

						templatexml = templatexml.Replace("{CCWebSiteURL}", websiteurl);
						templatexml = templatexml.Replace("{UserNameEN}",userrole.Employee.NameEN);
						templatexml = templatexml.Replace("{UserNameCN}",userrole.Employee.NameCN);
					
						templatexml = templatexml.Replace("{DUserNameCN}", userrole.DelegateUser.NameCN);
						templatexml = templatexml.Replace("{DUserNameEN}", userrole.DelegateUser.NameEN);
						templatexml = templatexml.Replace("{DRole}",userrole.Role.Description);
						templatexml = templatexml.Replace("{StartDate}",userrole.DelegateStartDate.Value.ToString("M/d/yyyy"));
						templatexml = templatexml.Replace("{EndDate}",userrole.DelegateEndDate.Value.ToString("M/d/yyyy"));

						if (userrole.DelegateUser.Email == null || userrole.DelegateUser.Email == string.Empty)	continue;
						if (!this.SendMail(_SenderEmail, userrole.DelegateUser.Email, userrole.Employee.Email, "Customer Case: User Role Delegation", templatexml))
						{
							string path1 = System.Environment.CurrentDirectory+"\\asbcc_error.log";
							StringBuilder sb = new StringBuilder();
							sb.Append("============================================\r\n");
							sb.AppendFormat("Sended fail--To:{0}Subject:{1}--EmailID:{2}\r\n",userrole.DelegateUser.Email,"Customer Case: User Role Delegation", "Reminder_UserRoleDelegation.xml");
							FileStream fs = File.Open(path1,FileMode.Append,FileAccess.Write);	
							StreamWriter sw = new StreamWriter(fs);
							sw.Write(sb.ToString());
							sw.Close();
							fs.Close();								
						}
						else
						{
							// Write Log
							BEGDC.CC.BL.Common.IUtility utility = AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.UtilityService] as BEGDC.CC.BL.Common.IUtility;
							BEGDC.CC.Entity.OperationLog log = new BEGDC.CC.Entity.OperationLog();
							log.Module = "Reminder";
						
							BEGDC.CC.Entity.Employee empemail = new BEGDC.CC.Entity.Employee();
							empemail.Id = "EmailService";
							log.Employee = empemail;
							log.Time = System.DateTime.Now;
							log.Description = "Send To:" + userrole.DelegateUser.Email + ". subject:Customer Case: User Role Delegation" ;
						
							utility.SaveOperationLog(log);
						}

					}
				}


				//
			}
			catch(Exception err)
			{
				try
				{
					string path1 = System.Environment.CurrentDirectory+"\\asbcc_error.log";
					StringBuilder sb = new StringBuilder();
					sb.Append("============================================\r\n");
					sb.AppendFormat("Error: {0}", err.Message);
					FileStream fs = File.Open(path1,FileMode.Append,FileAccess.Write);	
					StreamWriter sw = new StreamWriter(fs);
					sw.Write(sb.ToString());
					sw.Close();
					fs.Close();								

					string address = System.Configuration.ConfigurationSettings.AppSettings["AdminEmail"];
					SendMail("",address, "", "Error", err.Message);

				}
				catch
				{
				}

				throw err;
			}
			this._newtime = process_time ;

		}

		[Transaction(TransactionMode.Requires)]
		public void SendReminder_Day()
		{
			string websiteurl = System.Configuration.ConfigurationSettings.AppSettings["CCWebSiteURL"];

			try
			{
				//Delegration due date
				using ( ISession session = sessionManager.OpenSession() )
				{
					//Get user by modified

					string sql = "from UserRole where DelegateEndDate = '" + _newtime.AddDays(Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings["Email_Notification_Period_Day"])).ToString("M/d/yyyy") + "'";
					System.Collections.IList userroles = session.Find(sql);	
					foreach(BEGDC.CC.Entity.UserRole userrole in userroles)
					{
						string templatexml = this.LoadTemplate(Utility.GetTemplateFile("Reminder_UserRoleDelegationDueDate.xml"));

						templatexml = templatexml.Replace("{CCWebSiteURL}", websiteurl);
						templatexml = templatexml.Replace("{UserNameEN}",userrole.Employee.NameCN);
						templatexml = templatexml.Replace("{UserNameCN}",userrole.Employee.NameChinese);
						templatexml = templatexml.Replace("{DUserNameCN}", userrole.DelegateUser.NameEN);
						templatexml = templatexml.Replace("{DUserNameEN}", userrole.DelegateUser.NameChinese);
						templatexml = templatexml.Replace("{DRole}",userrole.Role.Description);
						templatexml = templatexml.Replace("{StartDate}",userrole.DelegateStartDate.Value.ToString("M/d/yyyy"));
						templatexml = templatexml.Replace("{EndDate}",userrole.DelegateEndDate.Value.ToString("M/d/yyyy"));

						if (userrole.Employee.Email == null || userrole.Employee.Email == string.Empty)	continue;
						if(!this.SendMail(_SenderEmail, userrole.Employee.Email,  userrole.DelegateUser.Email, "Customer Case: User Role Delegation Due Date", templatexml))
						{
							string path1 = System.Environment.CurrentDirectory+"\\asbcc_error.log";
							StringBuilder sb = new StringBuilder();
							sb.Append("============================================\r\n");
							sb.AppendFormat("Sended fail--To:{0}Subject:{1}--EmailID:{2}\r\n",userrole.DelegateUser.Email,"Customer Case: User Role Delegation Due Date", "Reminder_UserRoleDelegationDueDate.xml");
							FileStream fs = File.Open(path1,FileMode.Append,FileAccess.Write);	
							StreamWriter sw = new StreamWriter(fs);
							sw.Write(sb.ToString());
							sw.Close();
							fs.Close();								
						}
						else
						{
							// Write Log
							BEGDC.CC.BL.Common.IUtility utility = AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.UtilityService] as BEGDC.CC.BL.Common.IUtility;
							BEGDC.CC.Entity.OperationLog log = new BEGDC.CC.Entity.OperationLog();
							log.Module = "Reminder";
						
							BEGDC.CC.Entity.Employee empemail = new BEGDC.CC.Entity.Employee();
							empemail.Id = "EmailService";
							log.Employee = empemail;
							log.Time = System.DateTime.Now;
							log.Description = "Send To:" + userrole.DelegateUser.Email + ". subject:Customer Case: User Role Delegation Due Date" ;
						
							utility.SaveOperationLog(log);
						}

					}
				}

				BEGDC.CC.BL.Common.Query.IQuery iquery = AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.QueryService] as  BEGDC.CC.BL.Common.Query.IQuery;

				//Survey
				using ( ISession session = sessionManager.OpenSession() )
				{
					//Get flowmember by CRSurvey
					string sql = "select DISTINCT fm from fm in class BEGDC.CC.Entity.FlowMember , fi in class BEGDC.CC.Entity.FlowInstance, s in class BEGDC.CC.Entity.Step where  fm.Application.Id = fi.Application.Id and fm.Step.Id = s.Id and ((fi.CurrentActiveStep.StepCode = 'CRSurvey') OR (fi.CurrentActiveStep.StepCode = 'CVSurvey')) and ((s.StepCode = 'CRSurvey') OR (s.StepCode = 'CVSurvey')) and ((DATEDIFF(day, fi.LastModifiedDate, getdate()) = 1) or ((DATEDIFF(day, fi.LastModifiedDate, getdate()) % 5) = 0))  "; 
					System.Collections.IList members = session.Find(sql);	

					foreach(BEGDC.CC.Entity.FlowMember member in members)
					{
						string emails = string.Empty;

						string usernameen = string.Empty;
						string usernamecn = string.Empty;
						if (member.Employee == null)
						{
							BEGDC.CC.BL.UserManagement.IUser iuser = AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.UserService] as BEGDC.CC.BL.UserManagement.IUser;
							System.Data.DataTable dtEmails = iuser.GetEmailByRole(member.Role.RoleName);
							foreach(System.Data.DataRow drEmail in dtEmails.Rows)
							{	
								emails = drEmail[0].ToString() + ";";
							}
							usernameen = member.Role.Description;
							usernamecn = member.Role.Description;
						}
						else
						{
							emails = member.Employee.Email;
							if (emails == string.Empty)
								continue;

							usernameen = member.Employee.NameCN;
							usernamecn = member.Employee.NameChinese;
						}

						string templatexml = this.LoadTemplate(Utility.GetTemplateFile("Reminder_Survey_" + member.Application.ApplicationType + ".xml"));

						templatexml = templatexml.Replace("{CCWebSiteURL}", websiteurl);
						templatexml = templatexml.Replace("{UserNameEN}",usernameen);
						templatexml = templatexml.Replace("{UserNameCN}",usernamecn);

						templatexml = EmailTemplateResolver.ResolveEmailTemplate(templatexml,iquery.QueryFlowInstance(member.Application.Id)).Replace("\"", "'");

						if(!this.SendMail(_SenderEmail, emails, string.Empty, "Customer Case: Survey Reminder", templatexml))
						{
							string path1 = System.Environment.CurrentDirectory+"\\asbcc_error.log";
							StringBuilder sb = new StringBuilder();
							sb.Append("============================================\r\n");
							sb.AppendFormat("Sended fail--To:{0}Subject:{1}--EmailID:{2}\r\n",emails,"Customer Case: Reminder", "Reminder_Survey_" + member.Application.ApplicationType + ".xml");
							FileStream fs = File.Open(path1,FileMode.Append,FileAccess.Write);	
							StreamWriter sw = new StreamWriter(fs);
							sw.Write(sb.ToString());
							sw.Close();
							fs.Close();								
						}
						else
						{
							// Write Log
							BEGDC.CC.BL.Common.IUtility utility = AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.UtilityService] as BEGDC.CC.BL.Common.IUtility;
							BEGDC.CC.Entity.OperationLog log = new BEGDC.CC.Entity.OperationLog();
							log.Module = "Reminder";
						
							BEGDC.CC.Entity.Employee empemail = new BEGDC.CC.Entity.Employee();
							empemail.Id = "EmailService";
							log.Employee = empemail;
							log.Time = System.DateTime.Now;
							log.Description = "Send To:" + emails + ". subject:Customer Case: Survey Reminder" ;
						
							utility.SaveOperationLog(log);
						}

					}
				}

				//AP
				using ( ISession session = sessionManager.OpenSession() )
				{
					//AP
					string sql = "SELECT APID FROM (SELECT CASE (priority) WHEN 'High' THEN Days % 7 WHEN 'Normal' THEN Days % 14 WHEN 'Common' THEN Days % 21 END AS Days, APID FROM (SELECT CASE (priority) WHEN 'High' THEN datediff(day, getdate(), duetime) WHEN 'Normal' THEN datediff(day, getdate(), duetime) ";
					sql += "  WHEN 'Common' THEN datediff(day, getdate(), duetime) END AS Days, Priority, APID FROM ActionPoint WHERE (DueTime >= GETDATE()) AND (DueTime IS NOT NULL) AND (ClosedDate IS NULL) AND (status = 'open')) AS AP_Day) AS AP WHERE (Days = 0)";
					System.Data.DataTable dtAP = BEGDC.Utility.NHibernate.NHibernateUtil.Execute(session, sql);

					foreach(System.Data.DataRow drAP in dtAP.Rows)
					{
						int apid = Convert.ToInt32(drAP["APID"].ToString());

						BEGDC.CC.Entity.ActionPoint ap = session.Get( typeof(BEGDC.CC.Entity.ActionPoint), apid ) as BEGDC.CC.Entity.ActionPoint;
						string emails = string.Empty;
						string nameen = "All";
						string namecn = "All";

						foreach(BEGDC.CC.Entity.APPartner apPartner in ap.APPartners)
						{
							if (apPartner.Employee.Email != null)
								emails += apPartner.Employee.Email + ";";
							if (ap.APPartners.Count > 0)
							{
								nameen = "AP Owner/AP Contributer";
								namecn = "AP Owner/AP Contributer";
							}
						}
					

						if (emails == string.Empty) continue;

						string templatexml = this.LoadTemplate(Utility.GetTemplateFile("Reminder_AP.xml"));

						templatexml = templatexml.Replace("{CCWebSiteURL}", websiteurl);
						templatexml = templatexml.Replace("{Priority}", ap.Priority);
						templatexml = templatexml.Replace("{DueTime}", ap.DueTime.Value.ToString("M/d/yyyy"));
						templatexml = templatexml.Replace("{APNo}", ap.APNo);
						templatexml = templatexml.Replace("{APID}", ap.Id.ToString());
						templatexml = templatexml.Replace("{MeetingID}", ap.EVMeeting.Id.ToString());

						templatexml = templatexml.Replace("{UserNameEN}", nameen);
						templatexml = templatexml.Replace("{UserNameCN}", namecn);


						if(!this.SendMail(_SenderEmail, emails, string.Empty, "Customer Case: AP Reminder", templatexml))
						{
							string path1 = System.Environment.CurrentDirectory+"\\asbcc_error.log";
							StringBuilder sb = new StringBuilder();
							sb.Append("============================================\r\n");
							sb.AppendFormat("Sended fail--To:{0}Subject:{1}--EmailID:{2}\r\n",emails,"Customer Case: AP Reminder", "Reminder_AP.xml");
							FileStream fs = File.Open(path1,FileMode.Append,FileAccess.Write);	
							StreamWriter sw = new StreamWriter(fs);
							sw.Write(sb.ToString());
							sw.Close();
							fs.Close();								
						}
						else
						{
							// Write Log
							BEGDC.CC.BL.Common.IUtility utility = AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.UtilityService] as BEGDC.CC.BL.Common.IUtility;
							BEGDC.CC.Entity.OperationLog log = new BEGDC.CC.Entity.OperationLog();
							log.Module = "Reminder";
						
							BEGDC.CC.Entity.Employee empemail = new BEGDC.CC.Entity.Employee();
							empemail.Id = "EmailService";
							log.Employee = empemail;
							log.Time = System.DateTime.Now;
							log.Description = "Send To:" + emails + ". subject:Customer Case: AP Reminder" ;
						
							utility.SaveOperationLog(log);
						}

					}
				}
			}
			catch(Exception err)
			{
				try
				{
					string path1 = System.Environment.CurrentDirectory+"\\asbcc_error.log";
					StringBuilder sb = new StringBuilder();
					sb.Append("============================================\r\n");
					sb.AppendFormat("Error: {0}", err.Message);
					FileStream fs = File.Open(path1,FileMode.Append,FileAccess.Write);	
					StreamWriter sw = new StreamWriter(fs);
					sw.Write(sb.ToString());
					sw.Close();
					fs.Close();								

					string address = System.Configuration.ConfigurationSettings.AppSettings["AdminEmail"];
					SendMail("",address, "", "Error", err.Message);
					
				}
				catch
				{
				}
			}
			
		}
		#endregion
	}
}
